<?php
namespace app\common\model;

use think\Db;

class Auth
{
    /**
     * 特殊的商家分类不能删除
     * @param $type
     * @return mixed
     */
    static function token()
    {
        $str = md5(uniqid(md5(microtime(true)),true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密

        return $str;
    }

    /**
     * 获取token
     * @param $type
     * @param $id
     * @return string
     */
    static function token_key($type,$id)
    {
        $prefix = 'auth_identity_';

        return $prefix.$type.$id;
    }

    /**
     * 生成token登录
     * @param $type
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function token_login($type,$id,$login_data = [])
    {
        $redis = redis();
        if(is_array($redis)){
            errors($redis['message']);
        }
        $out_time = 7 * 86400;
        $time = time();

        $key = self::token_key($type,$id);
        $token = self::token();
        $data = [
            'token' => $token,
            'id' => $id,
            'data' => $login_data,
        ];
        //$redis->set($key,json_encode($data)) and $redis->expire($key,$out_time)
        if($redis->set($key,json_encode($data))){
            return $token;
        }
    }

    static function token_validate($type,$id,$token)
    {
        $redis = redis();
        if(is_array($redis)){
            errors([],$redis['message']);
        }
        $key = self::token_key($type,$id);
        $data = $redis->get($key);
        if(!$data){
            return [0,'找不到token'];
        }
        $data = json_decode($data,true);
        if(strcmp($data['token'],$token)){
            return [0,'token验证失败',$data['token']];
        }
        
        return [1,$data];
    }

    /*
     * @type        member_token
     * @id          uid
     * */
    static function token_out_login($type,$id,$login_data = []){
        $redis = redis();
        if(is_array($redis)){
            errors($redis['message']);
        }
        $key = self::token_key($type,$id);

        if($redis->del($key)){
            return true;
        }
    }

}